﻿using System;
using System.Threading.Tasks;
using CRM.Models.SocialMarketing;
using CRM.Services;
using Microsoft.AspNetCore.Mvc;
using VK.Client;
using VK.OAuth;
using VK.OAuth.Scopes;

namespace CRM.Controllers.SocialMarketing
{
    [ApiController]
    [Route("api/[controller]")]
    public class BindingAccountController : BaseController
    {
        private readonly UserService _userService;

        public BindingAccountController(UserService userService)
        {
            _userService = userService;
        }

        [HttpGet("[action]")]
        public ResultStruct SocialList()
        {
            var oauth = new VkOAuth();
            var clientId = 7853153;
            var redirectUri = "https://oauth.vk.com/blank.html";
            var display = VkOAuthDisplay.Page;
            var scope = new [] {VkOAuthUserScope.Wall, VkOAuthUserScope.Groups, VkOAuthUserScope.Offline};
            var state = "secret_state_code";
            var browserUrl = oauth.GetAuthorizeUrl(VkOAuthResponseType.Token, clientId, redirectUri, display, scope, state, revoke: true);
            return Success(new[]
            {
                new
                {
                    Name = "vk",
                    Url = browserUrl,
                    IsAuthed = !string.IsNullOrEmpty(_userService.CurrentUser.SocialAccount?.VkToken),
                    Avatar = _userService.CurrentUser.SocialAccount?.VkAvatar,
                    Username = _userService.CurrentUser.SocialAccount?.VkUsername,
                }
            });
        }

        public record AccountReqKv(string Type, string Value="");
        
        [HttpPost]
        public async Task<ResultStruct> BindAccount(AccountReqKv req)
        {
            if (req.Type == "vk")
            {
                var accessToken = Substr(req.Value, "access_token", "&");
                var client = new VkApiClient();
                var res = await client.Users.Get(accessToken);
                if (res.State)
                {
                    var account = new SocialAccount()
                    {
                        VkAvatar = res.Content[0].photo_50,
                        VkToken = accessToken,
                        VkUsername = res.Content[0].LastName,
                    };
                    await _userService.BindSocialAccount(account);
                    return Success();
                }
                else
                {
                    return Error(message: res.Error);
                }
            }
            else
            {
                return Error("未知类型");
            }
        }

        [HttpPost("[action]")]
        public async Task<ResultStruct> Cancel(AccountReqKv req)
        {
            if (req.Type == "vk")
            {
                var account = new SocialAccount()
                {
                    VkAvatar = string.Empty,
                    VkToken = string.Empty,
                    VkUsername = string.Empty,
                };
                await _userService.BindSocialAccount(account);
                return Success();
            }
            else
            {
                return Error("未知类型");
            }
        }

        public string Substr(string old, string start, string firstEnd)
        {
            var startIndex = old.IndexOf(start, StringComparison.Ordinal) + start.Length + 1;
            var firstEndIndex = old.IndexOf(firstEnd, startIndex, StringComparison.Ordinal);
            return old.Substring(startIndex, firstEndIndex - startIndex);
        }
    }
}